<template>
  <div class="submit-student-answer">
    <h2>提交学生答案</h2>

    <!-- 学生列表 -->
    <div v-if="students.length > 0" class="student-list">
      <div v-for="(student, index) in students" :key="student.id" class="student-item">
        <p>(学号: {{ student.stu_id }})</p>

        <!-- 上传文件按钮 -->
        <el-upload
            class="upload-demo"
            drag
            :http-request="customUpload(student.stu_id)"
            :show-file-list="true"
            :before-upload="beforeUpload"
        >
          <el-button size="small" type="primary">上传文件</el-button>
        </el-upload>

        <!-- 显示分数 -->
        <div class="score-display">
          <label>分数：{{ student.score || '等待评分' }}</label>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { BASE_URL } from '@/config';
import axios from 'axios';

export default {
  props: ['exam_id'],
  data() {
    return {
      students: [], // 存储学生列表
    };
  },
  created() {
    this.fetchStudentList(); // 获取学生列表
  },
  methods: {
    // 获取学生列表，包括分数，使用POST请求
    async fetchStudentList() {
      try {
        const response = await axios.post(`${BASE_URL}/exam/stuList`, {
          exam_id: this.$route.query.exam_id,
          course_id: this.$route.query.course_id,
        });
        if (response.data.code === 200) {
          // 假设返回的数据结构为 { code: 200, data: [学生数组] }
          this.students = response.data.data.map(student => ({
            ...student,
            score: student.score || 0, // 使用后端返回的分数，默认是0
          }));
        } else {
          this.$message.error('获取学生列表失败');
        }
      } catch (error) {
        console.error('获取学生列表失败:', error);
        this.$message.error('请求失败');
      }
    },

    // 自定义上传方法，上传文件使用POST请求
    customUpload(studentId) {
      return async ({ file, onSuccess, onError }) => {
        try {
          const base64Data = await this.readFileAsBase64(file);
          const fileName = file.name;
          console.log("Exam ID: ", this.$route.query.exam_id);
          console.log("Student ID: ", studentId);


          const requestData = {
            stu_id: studentId,
            exam_id: this.$route.query.exam_id,
            file: base64Data.split(',')[1],
          };

          const response = await axios.post(`${BASE_URL}/exam/ocr`, requestData);

          if (response.data.code === 200) {
            this.$message.success('文件上传成功');
            onSuccess(response.data);
          } else {
            this.$message.error('文件上传失败');
            onError(new Error('上传失败'));
          }
        } catch (error) {
          console.error('文件上传失败:', error);
          this.$message.error('上传请求失败');
          onError(error);
        }
      };
    },

    // 读取文件为Base64格式
    readFileAsBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (event) => {
          resolve(event.target.result);
        };
        reader.onerror = (error) => {
          reject(error);
        };
        reader.readAsDataURL(file);
      });
    },

    // 上传前的检查
    beforeUpload(file) {
      const isPDF = file.type === 'application/pdf';
      if (!isPDF) {
        this.$message.error('上传文件只能是 PDF 格式!');
      }
      return isPDF;
    }
  }
};
</script>

<style scoped>
.submit-student-answer {
  padding: 2vw;
  max-width: 90%;
  width: 600px;
  margin: 20px auto;
  border-radius: 8px;
  box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.1);
  background-color: #f5f5f5;
}

h2 {
  font-size: 2vw;
  color: #333;
  margin-bottom: 20px;
  text-align: center;
}

.student-list {
  margin-bottom: 2vw;
}

.student-item {
  margin-bottom: 1.5vw;
}

.score-display {
  margin-top: 10px;
}

.upload-demo {
  margin-top: 10px;
}

.el-button {
  margin-top: 15px;
}
</style>
